<template>
  <div class="container">
    <el-card style="position: relative">
      <RouterHeader :title="title()">
        <template v-slot:left-btn>
          <div v-if="route.query.name === '2'" class="yijieqing">
            <el-button @click="yijieqing" type="primary">已结清</el-button>
          </div>
        </template>
      </RouterHeader>
      <el-form
        :model="form"
        :rules="rules"
        ref="ruleFormRef"
        label-width="140px"
        label-position="right"
      >
        <el-row :gutter="20" class="form-single-info">
          <el-col :span="20">
            <div class="title"><h5>基本信息</h5></div>
            <el-row style="margin-left: 70px">
              <el-col :span="12">
                <el-descriptions>
                  <el-descriptions-item label="所属项目:">
                    <el-button
                      @click="correlation"
                      link
                      type="primary"
                      v-if="route.query.name === '1'"
                      >点此关联</el-button
                    >
                    <el-button v-else link>{{
                      form.affiliatedProject
                    }}</el-button>
                  </el-descriptions-item>
                </el-descriptions>
              </el-col>
              <el-col :span="12">
                <el-form-item label="项目名称" prop="projectName">
                  <el-input
                    class="input-item"
                    v-model="form.affiliatedProject"
                    placeholder="请输入"
                    disabled
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="业主单位" prop="ownersUnit">
                  <el-input
                    class="input-item"
                    v-model="form.ownersUnit"
                    placeholder="请输入"
                    disabled
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="项目联系人" prop="projectContact">
                  <el-input
                    class="input-item"
                    v-model="form.projectContact"
                    placeholder="请输入"
                    disabled
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="项目联系人电话"
                  prop="projectContactNumber"
                >
                  <el-input
                    class="input-item"
                    v-model="form.projectContactNumber"
                    placeholder="请输入"
                    disabled
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="合同金额" prop="contractAmount">
                  <el-input
                    class="input-item"
                    v-model="form.contractAmount"
                    placeholder="请输入"
                    :disabled="
                      route.query.name === '3' ||
                      route.query.name === '6' ||
                      route.query.name === '5'
                        ? true
                        : false
                    "
                  >
                    <template #append>元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="回款负责人" prop="collectionManager">
                  <el-input
                    class="input-item"
                    v-model="form.collectionManager"
                    placeholder="请输入"
                    disabled
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="签约日期" prop="arrDate">
                  <el-date-picker
                    v-model="form.arrDate"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    unlink-panels
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    :disabled="
                      route.query.name === '3' ||
                      route.query.name === '6' ||
                      route.query.name === '5'
                        ? true
                        : false
                    "
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="业务类型" prop="businessTypeList">
                  <el-cascader
                    v-model="form.businessTypeList"
                    ref="ref_business"
                    :options="businesstypeTree"
                    :props="businesstProps"
                    :show-all-levels="true"
                    disabled
                  ></el-cascader>
                </el-form-item>
              </el-col>
            </el-row>
            <div class="title"><h5>回款详情</h5></div>
            <el-row>
              <el-col :span="24">
                <el-form-item label="付款方式" prop="taskName">
                  <div style="width: 100%; position: relative">
                    <el-button
                      style="position: absolute; right: 0"
                      @click="onAddItem"
                      type="primary"
                      v-if="route.query.name === '1'"
                      >添加行</el-button
                    >
                    <el-table
                      :data="form.paymentDetailsList"
                      border
                      max-height="300px"
                      show-summary
                      :summary-method="getSummaries"
                      style="width: 100%; margin-top: 30px"
                    >
                      <el-table-column
                        width="160"
                        align="center"
                        label="回款次数"
                      >
                        <template #default="{ row, $index }">
                          第{{ $index + 1 }}次回款
                        </template>
                      </el-table-column>
                      <el-table-column
                        align="center"
                        prop="zifutime"
                        label="支付时间"
                        width="200"
                      >
                        <template #default="{ row }">
                          <el-input
                            v-model="row.zifutime"
                            placeholder="请输入支付时间"
                            :disabled="isDisabled()"
                          />
                        </template>
                      </el-table-column>
                      <el-table-column
                        align="center"
                        prop="yujihuiTime"
                        label="预计回款时间"
                        width="200"
                      >
                        <template #default="{ row }">
                          <el-date-picker
                            v-model="row.yujihuiTime"
                            type="date"
                            placeholder="请选择日期"
                            style="width: 140px"
                            format="YYYY-MM-DD"
                            value-format="YYYY-MM-DD"
                            :disabled="isDisabled()"
                          />
                        </template>
                      </el-table-column>
                      <el-table-column
                        align="center"
                        prop="zhishibili"
                        label="支付比例(%)"
                        width="200"
                      >
                        <template #default="{ row }">
                          <el-input
                            v-model="row.zhishibili"
                            placeholder="请输入支付比例"
                            :disabled="isDisabled()"
                          ></el-input>
                        </template>
                      </el-table-column>
                      <el-table-column
                        align="center"
                        prop="fangshi"
                        label="支付方式"
                        width="200"
                      >
                        <template #default="{ row }">
                          <el-input
                            v-model="row.fangshi"
                            placeholder="请输入支付方式"
                            :disabled="isDisabled()"
                          ></el-input>
                        </template>
                      </el-table-column>
                      <el-table-column
                        align="center"
                        prop="plannedReturn"
                        label="计划回款(元)"
                        width="200"
                      >
                        <template #default="{ row }">
                          <el-input
                            v-model.number="row.plannedReturn"
                            placeholder="请输入计划回款金额"
                            :disabled="isDisabled()"
                            ><template #append>元</template>
                          </el-input>
                        </template>
                      </el-table-column>
                      <el-table-column
                        align="center"
                        v-if="
                          route.query.name === '2' ||
                          route.query.name === '3' ||
                          route.query.show === '1'
                        "
                        prop="actualPaymentTime"
                        label="实际回款时间"
                        width="200"
                      >
                        <template #default="{ row }">
                          <el-date-picker
                            v-model="row.actualPaymentTime"
                            type="date"
                            placeholder="请选择日期"
                            style="width: 140px"
                            format="YYYY-MM-DD"
                            value-format="YYYY-MM-DD"
                            :disabled="
                              route.query.name === '3' ||
                              route.query.name === '6' ||
                              route.query.name === '5'
                                ? true
                                : false
                            "
                          />
                        </template>
                      </el-table-column>
                      <el-table-column
                        align="center"
                        v-if="
                          route.query.name === '2' ||
                          route.query.name === '3' ||
                          route.query.show === '1'
                        "
                        prop="actualPayoutRatio"
                        label="实际支付比例(%)"
                        width="200"
                      >
                        <template #default="{ row }">
                          <el-input
                            v-model.number="row.actualPayoutRatio"
                            placeholder="请输入实际支付比例"
                            :disabled="
                              route.query.name === '3' ||
                              route.query.name === '6' ||
                              route.query.name === '5'
                                ? true
                                : false
                            "
                          ></el-input>
                        </template>
                      </el-table-column>
                      <el-table-column
                        align="center"
                        v-if="
                          route.query.name === '2' ||
                          route.query.name === '3' ||
                          route.query.show === '1'
                        "
                        prop="receivedMoney"
                        label="已回款(元)"
                        width="200"
                      >
                        <template #default="{ row }">
                          <el-input
                            v-model.number="row.receivedMoney"
                            placeholder="请输入"
                            :disabled="
                              route.query.name === '3' ||
                              route.query.name === '6' ||
                              route.query.name === '5'
                                ? true
                                : false
                            "
                          >
                            <template #append>元</template>
                          </el-input>
                        </template>
                      </el-table-column>
                      <el-table-column
                        align="center"
                        v-if="
                          route.query.name === '2' ||
                          route.query.name === '3' ||
                          route.query.show === '1'
                        "
                        prop="moneyTobecollected"
                        label="待回款(元)"
                        width="200"
                      >
                        <template #default="{ row }">
                          <el-input
                            v-model.number="row.moneyTobecollected"
                            placeholder="请输入"
                            :disabled="
                              route.query.name === '3' ||
                              route.query.name === '6' ||
                              route.query.name === '5'
                                ? true
                                : false
                            "
                          >
                            <template #append>元</template>
                          </el-input>
                        </template>
                      </el-table-column>
                      <el-table-column
                        align="center"
                        v-if="
                          route.query.name === '2' ||
                          route.query.name === '3' ||
                          route.query.show === '1'
                        "
                        prop="timeDeviation"
                        label="回款时间偏差(天)"
                        width="200"
                      >
                        <template #default="{ row }">
                          <el-input
                            v-model.number="row.timeDeviation"
                            placeholder="请输入"
                            :disabled="
                              route.query.name === '3' ||
                              route.query.name === '6' ||
                              route.query.name === '5'
                                ? true
                                : false
                            "
                          ></el-input>
                        </template>
                      </el-table-column>
                      <el-table-column
                        align="center"
                        label="操作"
                        v-if="route.query.name === '1'"
                      >
                        <template #default="scope">
                          <el-button
                            link
                            type="primary"
                            size="small"
                            @click.prevent="deleteRow(scope.$index)"
                          >
                            删除行
                          </el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <div v-if="route.query.name !== '1'">
              <div class="title"><h5>回款计划审批进度</h5></div>
              <el-timeline style="max-width: 600px">
                <el-timeline-item
                  v-for="(item, index) in activities"
                  :key="index"
                  :color="item.color"
                  :timestamp="item.updateTime"
                >
                  <div style="display: flex; align-items: center">
                    <img :src="url + item.avatar" class="user-avatar" />
                    <span
                      style="
                        font-size: 14px;
                        font-weight: 500;
                        margin-left: 5px;
                      "
                    >
                      {{ item.username }} ({{
                        item.checkHisResult === "2" ? "未审核" : "已审核"
                      }}):</span
                    >
                    <span
                      style="
                        font-size: 14px;
                        font-weight: 400;
                        margin-left: 5px;
                      "
                    >
                      {{ item.opinion }}</span
                    >
                  </div>
                </el-timeline-item>
              </el-timeline>
            </div>
            <div v-if="route.query.name !== '1'">
              <div class="title"><h5>回款进度审批进度</h5></div>
              <el-timeline style="max-width: 600px">
                <el-timeline-item
                  v-for="(item, index) in activitie"
                  :key="index"
                  :color="activity.color"
                  :timestamp="item.updateTime"
                >
                  <div style="display: flex; align-items: center">
                    <img :src="url + item.avatar" class="user-avatar" />
                    <span
                      style="
                        font-size: 14px;
                        font-weight: 500;
                        margin-left: 5px;
                      "
                    >
                      {{ activity.username }} ({{
                        activity.checkHisResult === "2" ? "未审核" : "已审核"
                      }}):</span
                    >
                    <span
                      style="
                        font-size: 14px;
                        font-weight: 400;
                        margin-left: 5px;
                      "
                    >
                      {{ item.opinion }}</span
                    >
                  </div>
                </el-timeline-item>
              </el-timeline>
            </div>
            <div v-if="route.query.name !== '3'" class="title">
              <h5>
                {{
                  route.query.show === "2"
                    ? "回款计划审批流程"
                    : "回款进度审批流程"
                }}
              </h5>
            </div>

            <el-row v-if="route.query.name !== '3'">
              <el-col :span="24">
                <el-form-item label="审批方式">
                  <el-radio-group
                    v-model="form.processCheckBo.checkType"
                    :disabled="isDisabled()"
                  >
                    <el-radio :label="0">自由审批</el-radio>
                    <el-radio :label="1">逐级审批</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item
                  label="审批流程"
                  style="padding: 20px 0"
                  v-if="keepCheck === '1'"
                >
                  <approver
                    :approverList="form.processCheckBo.checkPeopleIds"
                    :typeId="3"
                    :isEdit="!!$route.query.projectId"
                    @handleChooseapprover="handleChooseapprover"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item
                  label="抄送"
                  style="padding: 20px 0"
                  v-if="keepCheck === '1'"
                >
                  <approver
                    :typeId="3"
                    :approverList="form.processCheckBo.copyFor"
                    :isCc="true"
                    @handleChooseapprover="handleChooseapproverCc"
                  ></approver>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="route.query.name === '6' || route.query.name === '5'">
              <el-col :span="24">
                <el-form-item label="审批意见" prop="projectImplementation">
                  <el-input
                    class="input-item"
                    type="textarea"
                    :autosize="{ minRows: 2 }"
                    show-word-limit
                    v-model="form.approvalOpinions"
                    placeholder="请输入"
                    :disabled="route.query.name === '5' ? true : false"
                  ></el-input>
                </el-form-item>
                <el-form-item
                  label="审批附件/图片"
                  prop="projectImplementation"
                >
                  <fileupload
                    @update:modelValue="approvalFilesAdd"
                    :modelValue="form.approvalFiles"
                  ></fileupload>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="审批决定" prop="projectImplementation">
                  <el-radio-group
                    v-model="keepCheck"
                    class="ml-4"
                    :disabled="route.query.name === '5' ? true : false"
                  >
                    <el-radio label="0" size="large">完成审批</el-radio>
                    <el-radio label="1" size="large">继续审批</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
        <div
          v-if="
            route.query.name === '1' ||
            route.query.name === '2' ||
            route.query.name === '6'
          "
          style="display: flex; justify-content: flex-end"
        >
          <el-button @click="resetForm(ruleFormRef)">{{
            route.query.name === "6" ? "驳回" : "取消"
          }}</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">{{
            route.query.name === "6" ? "通过" : "提交"
          }}</el-button>
        </div>
      </el-form>
      <el-dialog v-model="dialogTableVisible" title="关联项目" width="1000">
        <PropTable
          :columns="column"
          :data="form.gridData"
          :total="total"
          :show="false"
          @reset="reset"
          @onSubmit="onSubmit"
          @handleSizeChange="handleSizeChange"
          @handleCurrentChange="handleCurrentChange"
        >
          <template v-slot:projectCreateTime="scope">
            <div v-if="!useEmpty(scope.row.projectCreateTime)">
              {{ formatDate(scope.row.projectCreateTime) }}
            </div>
          </template>
          <template v-slot:operation="scope">
            <el-button
              link
              type="primary"
              size="small"
              @click="handleClick(scope.row)"
            >
              关联
            </el-button>
          </template>
        </PropTable>
      </el-dialog>
    </el-card>
  </div>
</template>
<script setup>
import RouterHeader from "@/components/RouterHeader";
import { useRoute, useRouter } from "vue-router";
import { ref, reactive, onMounted, h } from "vue";
import { businessTypeList } from "@/api/project/conversion";
import { useEmpty, formatDate } from "@/utils/index";
import { approvalList, approvalQuery } from "@/api/project/approval";
import {
  paymentAddApi,
  paymentDetailApi,
  updatePaymentApi,
  IdStatusApi,
} from "@/api/payment/payment";
import PropTable from "@/components/Table/PropTable/index.vue";
import approver from "@/components/Approve/approver.vue";
import { ElMessage } from "element-plus";
import { approvalProcessApi } from "@/api/approvalManagement/approvaType.js";
import fileupload from "@/components/FileUpload";
import { getUserProfile } from "@/api/system/user";
const router = useRouter();
const route = useRoute();
const keepCheck = ref("1");
const activities = ref([]);
const activitie = ref([]);
const title = () => {
  if (route.query.name === "1") {
    return "新建回款";
  } else if (route.query.name === "2") {
    return "回款进度";
  } else {
    return "回款详情";
  }
};
const disabled = ref(false);
// 表格输入框是否只读
const isDisabled = () => {
  if (route.query.name === "1") {
    return (disabled.value = false);
  } else {
    return (disabled.value = true);
  }
};
const dialogTableVisible = ref(false);
const ruleFormRef = ref();

const form = reactive({
  affiliatedProject: "", // 项目名称
  ownersUnit: "", // 业主单位
  projectContact: "", // 企业联系人
  projectContactNumber: "", // 联系人电话
  contractAmount: "", // 合同金额
  collectionManager: "", // 回款负责人
  arrDate: [], // 签约日期
  businessTypeList: [], // 业务类型
  gridData: [], // 关联项目的表格
  paymentDetailsList: [], // 回款计划表格
  processCheckBo: {
    checkPeopleIds: [], //审核人id列表
    copyFor: [], //抄送人id列表
    checkType: 1,
  },
  approvalOpinions: "", // 审批意见
  processCheckHistoryId: "", // 审批Id
  itemId: "", // 项目id
  refundId: "", // 回款Id
  heji: "", // 支付比例
  planHeji: "", // 计划回款合计
  payoutRatio: "", // 实际支付比例
  processed: "", // 已回款合计
  pending: "", // 待回款合计
  contractDate: "", // 签约日期开始时间
  entTime: "", // 签约日期结束时间
  approvalFiles: [],
  createBy: "", // 当前账号的ID
});
const rules = reactive({
  ownersUnit: [
    {
      required: true,
      message: "请输入业主单位",
      trigger: "blur",
    },
  ],
  projectContact: [
    {
      required: true,
      message: "请输入企业联系人",
      trigger: "blur",
    },
  ],
  projectContactNumber: [
    {
      required: true,
      message: "请输入联系人电话",
      trigger: "blur",
    },
  ],
  contractAmount: [
    {
      required: true,
      message: "请输入合同金额",
      trigger: "blur",
    },
  ],
  arrDate: [
    {
      // type: "date",
      required: true,
      message: "请选择签约日期",
      trigger: "change",
    },
  ],
  businessTypeList: [
    {
      required: true,
      message: "请选择业务类型",
      trigger: "change",
    },
  ],
});
// 获取用户信息
const getUser = async () => {
  const res = await getUserProfile();
  console.log(res);
  if (res.code === 200 && res.data) {
    form.collectionManager = res.data.userName;
    form.createBy = res.data.userId;
  }
};
// 添加行
const onAddItem = () => {
  if (form.paymentDetailsList.length >= 0) {
    form.paymentDetailsList.push({
      collectiontimes: `第${form.paymentDetailsList.length + 1}次回款`,
      zifutime: "", // 支付时间
      yujihuiTime: "", // 预计回款时间
      zhishibili: "", // 支付比例
      fangshi: "", // 支付方式
      plannedReturn: "", // 计划回款
      actualPaymentTime: "", // 实际回款时间
      actualPayoutRatio: "", // 实际支付比例
      receivedMoney: "", // 已回款
      moneyTobecollected: "", // 待回款
      timeDeviation: "", // 回款时间偏差
    });
  }
};
const getSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    if (
      column.label === "支付比例(%)" ||
      column.label === "计划回款(元)" ||
      column.label === "实际支付比例(%)" ||
      column.label === "已回款(元)" ||
      column.label === "待回款(元)"
    ) {
      const values = data.map((item) => Number(item[column.property]));
      sums[index] = values.reduce((prev, curr) => {
        const value = Number(curr);
        if (!isNaN(value)) {
          return prev + curr;
        } else {
          return prev;
        }
      }, 0);
      sums[index].toFixed(2);
      sums[index] += "";
    } else {
      sums[index] = "";
    }
    form.heji = sums[3];
    form.planHeji = sums[5];
    form.payoutRatio = sums[7];
    form.processed = sums[8];
    form.pending = sums[9];
  });
  return sums;
};

// 删除行
const deleteRow = (index) => {
  form.paymentDetailsList.splice(index, 1);
};
// 业务类型树形列表
const businesstypeTree = ref([]);
// 业务类型props配置
const businesstProps = {
  value: "id",
  label: "businessName",
  children: "children",
  // checkStrictly: true,
  multiple: true,
};
// 获取查询业务类型树形列表
const businessTypeOptions = async () => {
  const response = await businessTypeList();
  if (response.code === 200 && response.data.length > 0) {
    businesstypeTree.value = response.data;
  }
};
const column = [
  {
    name: "projectName",
    label: "项目名称",
    inSearch: true,
    valueType: "input",
  },
  { name: "projectId", label: "项目编号" },
  {
    name: "businessName",
    label: "业务类型",
    inSearch: true,
    valueType: "cascader",
    options: businesstypeTree,
    propsExpandTrigger: {
      value: "id",
      label: "businessName",
      checkStrictly: true,
      children: "children",
      emitPath: false,
    },
  },
  {
    name: "projectCreateTime",
    label: "创建时间",
    inSearch: true,
    valueType: "datetime",
    slot: true,
  },
  { name: "createPerson", label: "创建人" },
  { name: "operation", slot: true, label: "操作" },
];
// 点此关联
const correlation = () => {
  dialogTableVisible.value = true; // 关联
  approvalData();
};
// 关联项目的列表
const pageNum = ref(1);
const pageSize = ref(10);
const total = ref(0);
let paramsSubmit;
const approvalData = async () => {
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
  };
  if (paramsSubmit) {
    for (let key in paramsSubmit) {
      if (paramsSubmit[key]) {
        params[key] = paramsSubmit[key];
      }
    }
  }
  const res = await approvalList(params);
  if (res.code === 200 && res.rows.length >= 0) {
    form.gridData = res.rows;
    total.value = res.total;
  }
};
// 切换每页条数
const handleSizeChange = (valueSise) => {
  pageSize.value = valueSise;
  approvalData();
};
// 切换页码
const handleCurrentChange = (valuePage) => {
  pageNum.value = valuePage;
  approvalData();
};
// 点击查询
const onSubmit = (val) => {
  val.projectCreateTime = formatDate(val.projectCreateTime);
  paramsSubmit = val;
  approvalData();
};
// 点击重置
const reset = (val) => {
  val = "";
  approvalData();
};
// 是否关联项目
const flag = ref(false);
// 点此选择关联项目
const handleClick = async (row) => {
  let params = { id: row.proId };
  const res = await approvalQuery(params);
  if (res.code === 200 && typeof (res.data === "object")) {
    form.affiliatedProject = res.data.projectName; //  项目名称
    form.businessTypeList = res.data.test; // 业务类型
    form.ownersUnit = res.data.enterpriseName; // 业主单位
    // form.projectName = res.data.projectName;
    form.projectContactNumber = res.data.enterprisePhone; // 企业联系人电话
    form.projectContact = res.data.enterprisePerson;
    form.itemId = res.data.proId;
  }
  dialogTableVisible.value = false;
  flag.value = true;
};
// 审批人
const handleChooseapprover = (id) => {
  if (id) {
    form.processCheckBo.checkPeopleIds = id;
  }
};
// 抄送人
const handleChooseapproverCc = (id) => {
  if (id) {
    form.processCheckBo.copyFor = id;
  }
};
// 已结清
const yijieqing = async () => {
  let params = { id: Number(route.query.id) };
  const res = await IdStatusApi(params);
  console.log(res);
  if (res.code === 200) {
    ElMessage.success("操作成功");
    router.go(-1);
  }
};
// 回显
const checkDetail = async () => {
  let id = Number(route.query.id);
  const res = await paymentDetailApi(id);
  if (res.code === 200) {
    for (let key in form) {
      if (res.data[key]) {
        form[key] = res.data[key];
      }
    }
    form.processCheckBo.checkType=  res.data.dataCheckInfo1.checkType
    console.log(form.processCheckBo.checkType,'---form.processCheckBo.checkType---')
    if (form.entTime && form.contractDate) {
      form.arrDate = [form.contractDate, form.entTime];
    }
    form.businessTypeList = JSON.parse(res.data.businessType);
    form.refundId = Number(res.data.refundId);
    if (route.query.show === "1") {
      form.processCheckHistoryId =
        res.data.dataCheckInfo1.processCheckHistoryId;
      activities.value = res.data.dataCheckInfo1.opinons;
    } else {
      form.processCheckHistoryId =
        res.data.dataCheckInfo2.processCheckHistoryId;
      activities.value = res.data.dataCheckInfo2.opinons;
    }
    activities.value =
      res.data && res.data.dataCheckInfo1 && res.data.dataCheckInfo1.opinons;
    activitie.value =
      res.data && res.data.dataCheckInfo2 && res.data.dataCheckInfo2.opinons;
  }

  // 回款计划
  if (route.query.name === "5" && route.query.show === "2") {
    form.approvalOpinions =
      res.data &&
      res.data.dataCheckInfo1 &&
      res.data.dataCheckInfo1.myCheckOpinionBo &&
      res.data.dataCheckInfo1.myCheckOpinionBo.opinion;
    form.approvalFiles =
      res.data &&
      res.data.dataCheckInfo1 &&
      res.data.dataCheckInfo1.myCheckOpinionBo &&
      res.data.dataCheckInfo1.myCheckOpinionBo.fileList;
    keepCheck.value =
      res.data &&
      res.data.dataCheckInfo1 &&
      res.data.dataCheckInfo1.myCheckOpinionBo &&
      res.data.dataCheckInfo1.myCheckOpinionBo.keepCheck;
  }

  // 进度审批
  if (route.query.name === "5" && route.query.show === "1") {
    form.approvalOpinions =
      res.data &&
      res.data.dataCheckInfo2 &&
      res.data.dataCheckInfo2.myCheckOpinionBo &&
      res.data.dataCheckInfo2.myCheckOpinionBo.opinion;
    form.approvalFiles =
      res.data &&
      res.data.dataCheckInfo2 &&
      res.data.dataCheckInfo2.myCheckOpinionBo &&
      res.data.dataCheckInfo2.myCheckOpinionBo.fileList;
    keepCheck.value =
      res.data &&
      res.data.dataCheckInfo2 &&
      res.data.dataCheckInfo2.myCheckOpinionBo &&
      res.data.dataCheckInfo2.myCheckOpinionBo.keepCheck;
  }

  // 进度审批
  if (route.query.name === "6" && route.query.show === "1") {
    form.processCheckHistoryId = res.data.dataCheckInfo2.processCheckHistoryId;
  } else if (route.query.name === "6") {
    form.processCheckHistoryId = res.data.dataCheckInfo1.processCheckHistoryId;
  }
};
// 签约日期的回显函数
// const echoContractDate = () => {

// }
// 审批附件
const approvalFilesAdd = (val, result, operationType) => {
  if (operationType === "success") {
    if (result) {
      form.approvalFiles = [];
      result.forEach((item)=>{
        form.approvalFiles.push(item);
      });
    }
  } else if (operationType === "delete") {
    form.approvalFiles.splice(result, 1);
  }
};
// 取消/驳回
const resetForm = async () => {
  if (route.query.name === "6") {
    let data = {
      checkOpinion: form.approvalOpinions,
      id: form.processCheckHistoryId,

      copyFor: form.processCheckBo.copyFor.map((item) => item.userId),
      keepCheckId: form.processCheckBo.checkPeopleIds.map(
        (item) => item.userId
      ),
      state: "0",
      fileList: form.approvalFiles,
      keepCheck: keepCheck.value,
    };
    const res = await approvalProcessApi(data);
    if (res.code === 200) {
      ElMessage.success("审批已驳回");
      router.go(-1);
    }
  } else {
    router.go(-1);
  }
};
// 提交/通过
const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (route.query.name === "1") {
        if (flag.value === false) {
          ElMessage.error("请关联项目");
        } else {
          if (form.arrDate.length === 2) {
            form.contractDate = form.arrDate[0];
            form.entTime = form.arrDate[1];
            let userCcIds;
            let userIds;
            let newArray = [];
            let requestPayload;
            if (form.processCheckBo.checkPeopleIds) {
              userIds = form.processCheckBo.checkPeopleIds.map((item) =>
                item.userId ? Number(item?.userId) : item
              );
            }
            if (form.processCheckBo.copyFor) {
              userCcIds = form.processCheckBo.copyFor.map((item) =>
                item.userId ? Number(item?.userId) : item
              );
            }
            if (form.processCheckBo.checkType === 1) {
              // 逐级审批 orderCheckPeopleInfoList
              // 使用 map 方法重构数组
              newArray = form.processCheckBo.checkPeopleIds.map((item, index) => {
                return {
                  orderNum: index + 1,
                  userId: item.userId ?  Number(item?.userId) :item,
                };
              });
              requestPayload = {
                ...form,
                processCheckBo: {
                  orderCheckPeopleInfoList: newArray, // 直接作为顶层属性
                  copyFor: userCcIds, // 直接作为顶层属性
                  checkType: form.processCheckBo.checkType,
                },
              };
            } else {
              requestPayload = {
                ...form,
                processCheckBo: {
                  checkPeopleIds: userIds, // 设置新的 checkPeopleIds 属性值
                  copyFor: userCcIds,
                  checkType: form.processCheckBo.checkType,
                },
              };
            }
            const res = await paymentAddApi(requestPayload);
            if (res.code === 200) {
              ElMessage.success(res.msg);
              router.go(-1);
            }
          }
        }
      } else if (route.query.name === "2") {
        let userCcIds;
        let userIds;
        if (form.processCheckBo.checkPeopleIds) {
          userIds = form.processCheckBo.checkPeopleIds.map((item) =>
            item.userId ? Number(item?.userId) : item
          );
        }
        if (form.processCheckBo.copyFor) {
          userCcIds = form.processCheckBo.copyFor.map((item) =>
            item.userId ? Number(item?.userId) : item
          );
        }
        if (form.arrDate.length === 2) {
          form.contractDate = form.arrDate[0];
          form.entTime = form.arrDate[1];
          let data = {
            ...form,
            processCheckBo: {
              checkPeopleIds: userIds, // 设置新的 checkPeopleIds 属性值
              copyFor: userCcIds,
            },
          };
          const res = await updatePaymentApi(data);
          console.log(res);
          if (res.code === 200) {
            ElMessage.success("操作成功");
            router.go(-1);
          }
        }
      } else if (route.query.name === "6") {
        let data = {
          checkOpinion: form.approvalOpinions,
          id: form.processCheckHistoryId,
          copyFor: form.processCheckBo.copyFor.map((item) => item.userId),
          keepCheckId: form.processCheckBo.checkPeopleIds.map(
            (item) => item.userId
          ),
          state: "1",
          fileList: form.approvalFiles,
          keepCheck: keepCheck.value,
        };
        const res = await approvalProcessApi(data);
        if (res.code === 200) {
          ElMessage.success("审批通过");
          router.push({
            path: "/examine",
          });
        }
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

onMounted(async () => {
  await businessTypeOptions();
  await getUser();
  if (route.query.name !== "1") {
    await checkDetail();
  }
});
</script>
<style lang="scss" scoped>
.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 10px;
}
.container {
  padding: 20px;
  .yijieqing {
    display: flex;
    justify-content: flex-end;
  }
  .form-single-info {
    display: flex;
    justify-content: center;
  }
  .title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    h5 {
      font-weight: bold;
    }
  }
}
</style>
